import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home/index'
import Login from '@/components/Login/index'
import Mydouban from '@/components/Mydouban/index'
import Shopcar from '@/components/Shopcar/index'
import Shopcart from '@/components/Shopcart/index'
import GoodsDetail from '@/components/GoodsDetail/index'
import Store from '../store/index'
import { Message, MessageBox } from 'element-ui'
import Cookies from 'js-cookie';
Vue.use(Router)
const router = new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,

    },
    {
      path: '/home',
      name: 'Home',
      component: Home,

    }, {
      path: '/login',
      name: 'Login',
      component: Login,

    },
    {
      path: '/mydouban',
      name: 'Mydouban',
      component: Mydouban,
      meta: {
        roles: ['super', 'normal','admin'],
        login: true
      }

    },
    {
      path: '/shopcar',
      name: 'Shopcar',
      component: Shopcar,

    },
    {
      path: '/shopcart',
      name: 'Shopcart',
      component: Shopcart,
      meta: {
        login: true
      }
    },
    {
      path:'/goodsDetail',
      name:'GoodsDetail',
      component:GoodsDetail,
    }
  ]
})

router.beforeEach((to, from, next) => {
  console.log(to,from)
  console.log(Store.state.user.isLogin)
  //是否需要登录后进入的页面
  if (to.meta.login && !Store.state.user.isLogin) {
    next({ path: '/login?dir=' + to.path })
    return false
  }
  if(Cookies.get('x-token') && to.path =='/login'){
    next({path:'/'})
  }
  //用户是否拥有权限
  if (to.meta && to.meta.roles) {
    const permission = to.meta.roles.some(role => { return Store.state.user.roles.includes(role) })
    //console.log(permission)
    if (permission) {
      next()
    } else {
      Message({
        message: '请联系管理员添加权限',
        type: 'error',
        duration: 5 * 1000
      })
      next({ 'path': '/' })
    }
  } else {
    next()
  }
})

router.afterEach((to, from, next) => {
  
})
export default router